package com.notes.config.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.notes.config.api.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: huxingxin
 * @Date: 2024/1/11
 *
 *  全局异常处理
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ApiResult exception(Exception e){
        e.printStackTrace();
        String message = getRootCauseMessage(e);
        return ApiResult.error(message);
    }

    private String getRootCauseMessage(Throwable throwable) {
        Throwable rootCause = ExceptionUtils.getRootCause(throwable);
        if (rootCause == null) {
            rootCause = throwable;
        }
        return rootCause.getClass().getSimpleName() + ": " + rootCause.getMessage();
    }

    /**
     * 对于参数校验异常的处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleValidationExceptions(MethodArgumentNotValidException e) throws JsonProcessingException {
        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String message = objectMapper.writeValueAsString(errors);
        return ApiResult.error(message.replace("\"", ""));
    }


    /**
     * 绑定异常处理方法
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ApiResult handleBindException(BindException e) throws JsonProcessingException {
        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String message = objectMapper.writeValueAsString(errors);
        return ApiResult.error(message.replace("\"", ""));
    }
}
